<template>
    <el-row :gutter="20">
        <el-col :span="16">
            <el-card>
                <div slot="header">
                    <el-button icon="el-icon-plus" @click="addMonitorConf()" size="mini">新增监控配置</el-button>
                </div>
                <el-table @sort-change = "sortChange" :data="monitorConfList" v-loading="isLoading" element-loading-text="列表加载中..." style="width: 100%" max-height="680" border fit highlight-current-row>
                    <el-table-column align="center" width="80px" label="操作" fixed>
                        <template slot-scope="scope">
                            <el-button type="text" size="mini" icon="edit" @click="editMonitorConf(scope.row)" title="编辑">编辑</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" width="80px" prop="monitor_id" label="ID" sortable='custom' fixed></el-table-column>
                    <el-table-column align="left" width="200px" prop="monitor_desc" label="监控描述" sortable='custom' fixed></el-table-column>
                    <el-table-column align="left" width="200px" prop="station_list" label="站点" sortable='custom' >
                        <template slot-scope="scope">
                            <span v-if="scope.row.station_list && scope.row.station_list!=null && scope.row.station_list.length > 0">
                                <span v-for="(id, index) in scope.row.station_list.split(',')">
                                    <label v-if="index > 0">,</label>
                                    <a :href="`//${hostname}/crawl/grabSourceConf/${id}`" target="_blank" title="点击查看站点详情">{{id}}</a>
                                </span>
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column align="left" width="200px" prop="check_cron" label="扫描频率" sortable='custom'></el-table-column>
                    <el-table-column align="center" width="100px" prop="is_valid" label="是否激活" sortable='custom'>
                        <template slot-scope="scope">
                            <c-icon v-if="scope.row.is_valid == 1" name="check" style="color:#00AE66;"></c-icon>
                            <c-icon v-else name="times" style="color:#e74c3c;"></c-icon>
                        </template>
                    </el-table-column>
                    <el-table-column align="left" width="200px" prop="crawlerStorageModel.desc" label="模型" sortable='custom'></el-table-column>
                    <el-table-column align="left" width="200px" prop="crawlerStorageModel.table_name_prefix" label="物理表前缀" sortable='custom'></el-table-column>
                    <el-table-column align="center" width="100px" prop="crawlerStorageModel.table_create_rand" label="分表周期" sortable='custom'></el-table-column>
                    <el-table-column align="center" width="100px" prop="creator" label="创建人" sortable='custom'></el-table-column>
                    <el-table-column align="center" width="150px" prop="creat_time" label="创建时间" sortable='custom'>
                        <template slot-scope="scope">
                            {{formatDate(scope.row.creat_time)}}
                        </template>
                    </el-table-column>
                    <el-table-column align="center" width="100px" prop="updator" label="更新人" sortable='custom'></el-table-column>
                    <el-table-column align="center" width="150px" prop="update_time" label="更新时间" sortable='custom'>
                        <template slot-scope="scope">
                            {{formatDate(scope.row.update_time)}}
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </el-col>
        <el-col :span="8">
            <el-card>
                <div slot="header" style="font-weight:bold;font-size:15px;">
                    {{editPageTitle}} 
                </div>
                <el-form ref="monitorConfForm" label-position="left" label-width="90px" >
                    <el-form-item label="监控描述">
                        <el-input v-model="monitorConf.monitor_desc" style="width:300px;" size="mini"></el-input><br>
                        <span class="alert" style="padding-left: 0px;">
                            <i class="el-icon-info"></i> 会展示在告警中，请勿重复
                        </span>
                    </el-form-item>
                    <el-form-item label="站点">
                        <el-select v-model="grabSourceSelectedList" multiple placeholder="请选择" style="width:400px;" filterable size="mini">
                            <el-option
                            v-for="item in grabSourceList"
                            :key="item.station_id"
                            :label="`${item.station_id}--${item.station_name_cn}`"
                            :value="`${item.station_id}`">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="模型">
                        <el-select v-model="monitorConf.model_id" placeholder="请选择" size="mini" filterable>
                            <el-option v-for="item in storageModelList" :label="item.desc" :value="item.model_id" :key="item.model_id" >
                                <span>{{ item.model_id }}--{{ item.desc }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="CRON">
                        <el-input v-model="monitorConf.check_cron" style="width:240px;" size="mini"></el-input>
                        <el-button type="primary" @click="showCronNextTime" size="mini">测试</el-button><br>
                        <span class="alert" style="padding-left: 0px;">
                        <i class="el-icon-info"></i>&nbsp;
                        例子：<br>
                        每天的9点到18点每个整点过30分执行一次：0 30 9-18 * * *<br>
                        周一和周二的10:00和12:00各执行一次：0 0 10,12 * * 1,2<br>
                        周一至周五每2小时执行一次：0 0 */2 * * 1-5<br>
                        每天的8:10执行一次：0 10 8 * * *<br>
                        </span>
                    </el-form-item>
                    <el-form-item label="是否激活">
                        <el-switch v-model="monitorConf.is_valid" :active-value = "1" :inactive-value = "0"></el-switch>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" :disabled="submitLoading" :loading="submitLoading" @click="submitForm">保存</el-button>
                        <span class="alert">
                            <i class="el-icon-info"></i> 点击保存会立即重启相应的监控job
                        </span>
                    </el-form-item>
                </el-form>
            </el-card>
        </el-col>
    </el-row>
</template>

<script>
import icon from 'vue-awesome';
import dayjs from 'dayjs';
import lodash from 'lodash';
import cronParser from 'cron-parser';
import { getMonitorConfList, saveMonitorConf, getGrabSourceList, getStorageModelList } from '../../api/crawl.js';
export default {
components: {
    'c-icon' : icon
},
data() {
    return {
        hostname : location.hostname,//域名
        cronParser,
        isLoading : true,
        monitorConfList : [],
        grabSourceList : [],
        storageModelList : [],
        //编辑监控配置
        monitorConf : {
            monitor_id : '',
            monitor_desc : '',
            station_list : '',
            model_id : '',
            check_cron : '',
            is_valid : 1
        },
        grabSourceSelectedList : [],
        editPageTitle : '新增监控配置',
        submitLoading : false,
    }
},
created() {
    this.initMonitorConfList();
    this.initGrabSourceList();
    this.initStorageModelList();
},
watch: {
},
computed: {
},
mounted() {

},
methods: {
    initMonitorConfList(){
        this.isLoading = true;
        getMonitorConfList().then(data=>{
            console.log('getMonitorConfList---------',data);
            this.isLoading = false;
            this.monitorConfList = data.rows;
        }).catch(e=>{
            console.log(e);
        });
    },
    initGrabSourceList(){
        getGrabSourceList().then(data=>{
            this.grabSourceList = data.rows;
            this.grabSourceList = this.grabSourceList.filter(item => Number(item.status) === 1 );
        })
    },
    initStorageModelList(){
        getStorageModelList().then(data=>{
            this.storageModelList = data.rows;
        })
    },
    //新增监控配置
    addMonitorConf() {
        this.editPageTitle = '新增监控配置'
        this.grabSourceSelectedList = [];
        this.monitorConf.monitor_id = '';
        this.monitorConf.monitor_desc = '';
        this.monitorConf.station_list = '';
        this.monitorConf.model_id='';
        this.monitorConf.check_cron='';
        this.monitorConf.is_valid = 1;
    },
    //修改监控配置
    editMonitorConf(row) {
        this.editPageTitle = `编辑监控配置 [${row.monitor_id}--${row.monitor_desc}]`;
        this.grabSourceSelectedList = [];
        this.monitorConf.monitor_id = row.monitor_id;
        this.monitorConf.monitor_desc = row.monitor_desc;
        this.monitorConf.station_list = row.station_list;
        this.monitorConf.model_id= row.model_id;
        this.monitorConf.check_cron= row.check_cron;
        this.monitorConf.is_valid = row.is_valid;
        //加载站点列表下拉框
        if(this.monitorConf.station_list){
            this.grabSourceSelectedList = this.monitorConf.station_list.split(',');
        }
    },
    //保存监控配置
    async submitForm(){
        console.log('monitorConf---', this.monitorConf)
        this.monitorConf.station_list = this.grabSourceSelectedList.join(',');
        let cron = this.monitorConf.check_cron.trim();
        let errorMsg = '';
        if(!this.monitorConf.monitor_desc.trim()){
            errorMsg = '请填写监控描述！';
        }else if(!this.monitorConf.station_list){
            errorMsg = '请选择站点！';
        }else if(!this.monitorConf.model_id){
            errorMsg = '请选择模型！';
        }else if(!cron){
            errorMsg = '请填写cron！';
        }else if(cron){
            try{
                var interval = this.cronParser.parseExpression(cron);
            }catch(e){
                errorMsg = `cron有误：${e.message}`;
            }
        }
        if(errorMsg){
            this.$message.error(errorMsg);
        }else{
            this.monitorConf.monitor_desc = this.monitorConf.monitor_desc.trim();
            this.monitorConf.check_cron = this.monitorConf.check_cron.trim();
            const postData = Object.assign({}, this.monitorConf);
            this.submitLoading = true;
            const res = await saveMonitorConf(postData);
            console.log('saveMonitorConf---', res)
            if(res){
                //提示保存成功
                this.$alert('保存成功！', '提示', {
                    confirmButtonText: '确定'
                });
                this.initMonitorConfList();
            }
            this.submitLoading = false;
        }
    },
    formatDate(dateTime){
        if(!dateTime){
            return '--';
        }
        return dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss');
    },
    //排序
    sortChange(data){
        let {order, prop} = data;
        //如果是顺序则按照顺序排，否则就按照倒序排
        if(order === 'descending'){
            this.monitorConfList = lodash.orderBy(this.monitorConfList, [prop], 'desc');
        }else{
            this.monitorConfList = lodash.orderBy(this.monitorConfList, [prop], 'asc');
        }
        this.pageNo = 1;
    },
    showCronNextTime(){
        let cron = this.monitorConf.check_cron.trim();
        if(cron){
            let expression = '';
            try{
                var interval = this.cronParser.parseExpression(cron);
                let count = 0;
                while(count < 15){
                    count ++;
                    expression += this.formatDate(interval.next().toString())+'<br/>';
                }
            }catch(e){
                expression = e.message;
            }
            this.$notify({
                title: '下次执行时间',
                dangerouslyUseHTMLString: true,
                message: expression
            });
        }
    }
}
};
</script>
<style>

</style>



